package com.sxhuayuan.parking.plugin.parking.dao_er.request;

import com.sxhuayuan.parking.entity.ParkingLot;
import com.sxhuayuan.parking.exception.SystemException;
import com.sxhuayuan.parking.plugin.annotation.SignatureField;
import com.sxhuayuan.parking.plugin.parking.AbstractRequest;
import com.sxhuayuan.parking.plugin.parking.dao_er.DaoerParkingPlugin;
import com.sxhuayuan.parking.utils.Md5Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

/**
 * 道尔
 * 
 * @author 何龙
 * @date 2019-07-15 10:20
 */
public abstract class DaoerBaseRequest extends AbstractRequest {

	/** 请求方式 */
	public enum RequestMethod {
		/** 请求方式 */
		GET, POST
	}

	/** 签名 */
	@SignatureField
	private String signature = "";

	/** 时间戳 秒 */
	private Long t = System.currentTimeMillis() / 1000;

	public Long getT() {
		return t;
	}

	private void setT(Long t) {
		this.t = t;
	}

	public String getSignature() {
		return signature;
	}

	private void setSignature(String signature) {
		this.signature = signature;
	}

	/** 请求接口url,不包括url前缀和 /{parkid} */
	public abstract String requestUrl();

	/** 获取接口请求方式 */
	public abstract RequestMethod getRequestMethod();

	@Override
	public void checkAndSign(boolean ignoreEmptyValue, boolean dictionarySort, String suffix, String secret) throws SystemException {
	}

	/** 检查约束、签名、返回接口url */
	public String checkAndSign(ParkingLot parkingLot) throws SystemException {
		Assert.notNull(parkingLot,"车场不能为空");
		Assert.notNull(parkingLot.getApiUrl(),"车场接口不能为空");
		Assert.notNull(parkingLot.getApiUser(),"车场用户不能为空");
		Assert.notNull(parkingLot.getApiKey(),"车场秘钥不能为空");

		// 检查约束
		this.checkFields();
		String s = requestUrl();
		if (StringUtils.isEmpty(s)) {
			throw new SystemException("请求接口不能为空");
		}
		// 签名
		String requestString = String.format(parkingLot.getApiUrl() + requestUrl() + "/%s", parkingLot.getApiUser());
		String str = String.format("%s@#%s@#%s", requestString, t, parkingLot.getApiKey());
		this.setSignature(Md5Utils.md5(str));
		return requestString;
	}
}
